package com.example.controller;

import cn.hutool.cache.impl.TimedCache;
import com.example.entity.User;
import com.example.service.UserService;
import com.example.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.concurrent.ConcurrentHashMap;


@RestController
@RequestMapping("/user")
public class UserController {

    /**
     * 登录用户信息缓存，24小时过期
     */
    private static final TimedCache<String, User> LONG_USER_TIMED_CACHE = new TimedCache<>(1000 * 60 * 60 * 24L, new ConcurrentHashMap<>());

    @Autowired
    private UserService userService;

    @PostMapping("/register")
    public Result register(@RequestBody User user) {
        boolean isSuccess = userService.saveUser(user);
        if (isSuccess) {
            return Result.ok("注册成功！");
        } else {
            return Result.error("用户已存在，可直接登录！");
        }
    }

    @PostMapping("/login")
    public Result login(@RequestBody User user) {
        User userByIdByPass = userService.getUserByIdByPass(user);
        if (userByIdByPass != null) {
            cacheUserInfo(userByIdByPass);
            return Result.ok(userByIdByPass);
        } else {
            return Result.error("账号或密码错误");
        }
    }

    @PostMapping("/listAllUsers")
    public Result listAllUsers() {
        List<User> users = userService.listAllUsers();
        return Result.ok(users);
    }

    private void cacheUserInfo(User user) {
        LONG_USER_TIMED_CACHE.put(user.getUserId(), user);
    }

}
